package com.dao;

import java.sql.Timestamp;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.base.BaseDao;
import com.bean.RoleInfo;
import com.bean.SysUser;
import com.bean.UserLogin;
import com.util.EncoderHandler;
import com.util.GUtil;

/**
 * A data access object (DAO) providing persistence and search support for
 * SysUser entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.bean.SysUser
 * @author MyEclipse Persistence Tools
 */
public class SysUserDao extends BaseDao {
	private static final Logger log = LoggerFactory.getLogger(SysUserDao.class);
	// property constants
	public static final String USER_NAME = "userName";
	public static final String USER_PASSWD = "userPasswd";
	public static final String REAL_NAME = "realName";
	public static final String ROLE = "role";
	public static final String INTRODUCTION = "introduction";
	public static final String PHONE = "phone";
	public static final String EMAIL = "email";
	public static final String STATUS = "status";
	
	/**
	 * 登录
	 * <p>Title: login</p>
	 * <p>Description: </p>
	 * @param userName
	 * @param password
	 * @param ip
	 * @return
	 */
	public SysUser login(String userName, String password, String ip){
		SysUser user=null;
		String queryString = "from SysUser as model where model.userName=? and userPasswd=?";
		Query query = getSession().createQuery(queryString);
		String pwd = EncoderHandler.EncoderPasswordBase64Md5( password );
		query.setParameter(0, userName);
		query.setParameter(1, pwd); //  query.setParameter("pwd", EncoderHandler.MD5(user.getUserPasswd()));
		
	//	System.out.println("SysUser Login "+userName+" EncoderHandler.EncoderPasswordBase64Md5("+password+")="+pwd);
		user = (SysUser) query.uniqueResult();
		UserLogin userLogin = new UserLogin();
		if(user!=null){
			if(user.getStatus()!=1){
				log.error("用户："+userName+" 请求登录，状态不正常["+user.getStatus()+"]");
				return null;
			}
			query = getSession().createQuery("from RoleInfo r where r.roleId= "+user.getRole());
			RoleInfo roleInfo = (RoleInfo)query.uniqueResult();
			System.out.println("roleInfo = "+roleInfo);
			if(roleInfo!=null){
				System.out.println("getRoleName = "+roleInfo.getRoleName());
				user.setRoleName(roleInfo.getRoleName());
			}
//			System.out.println("query="+query.getQueryString());
			userLogin.setLoginId(user.getSysUserId());
			userLogin.setLoginIp(ip);
			userLogin.setLoginTime(new Timestamp(System.currentTimeMillis()));
		//	getSession().save(userLogin);
			
		}
		
		return user;
	}

	/**
	 * 查询用户
	 * <p>Title: query</p>
	 * <p>Description: </p>
	 * @param SysUser
	 * @return
	 */
	public List<SysUser> query(SysUser SysUser){
		return this.findAll();
	}
	
	/**
	 * 保存
	 * <p>Title: save</p>
	 * <p>Description: </p>
	 * @param transientInstance
	 * @return
	 */
	public String save(SysUser transientInstance) {
		log.debug("saving SysUser instance");
		try {
			Timestamp tm = new Timestamp(System.currentTimeMillis());
			transientInstance.setCreateTime(tm);
			transientInstance.setUpdateTime(tm);
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}
	/**
	 * 保存
	 * <p>Title: save</p>
	 * <p>Description: </p>
	 * @param transientInstance
	 * @return
	 */
	public String update(SysUser transientInstance) {
		log.debug("update SysUser instance");
		try {
			Timestamp tm = new Timestamp(System.currentTimeMillis());
			transientInstance.setUpdateTime(tm);
			getSession().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public String delete(Long id) {
		SysUser persistentInstance = this.findById(id);
		if(persistentInstance==null)
			return GUtil.FAILE;
		this.delete(persistentInstance);
		return GUtil.SUCCESS;
	}
	public void delete(SysUser persistentInstance) {
		log.debug("deleting SysUser instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public SysUser findById(java.lang.Long id) {
		log.debug("getting SysUser instance with id: " + id);
		try {
			SysUser instance = (SysUser) getSession()
					.get(SysUser.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(SysUser instance) {
		log.debug("finding SysUser instance by example");
		try {
			List results = getSession().createCriteria(SysUser.class)
					.add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding SysUser instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from SysUser as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUserName(Object userName) {
		return findByProperty(USER_NAME, userName);
	}

	public List findByUserPasswd(Object userPasswd) {
		return findByProperty(USER_PASSWD, userPasswd);
	}

	public List findByRealName(Object realName) {
		return findByProperty(REAL_NAME, realName);
	}

	public List findByRole(Object role) {
		return findByProperty(ROLE, role);
	}

	public List findByIntroduction(Object introduction) {
		return findByProperty(INTRODUCTION, introduction);
	}

	public List findByPhone(Object phone) {
		return findByProperty(PHONE, phone);
	}

	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List findAll() {
		session = getSession();
		log.debug("finding all SysUser instances");
		try {
			String queryString = "from SysUser where status!=-1";
			Query queryObject = session.createQuery(queryString);
			List<SysUser> list = queryObject.list();
			for(SysUser su : list){
				if(su.getRole()==null)
					continue;
				RoleInfo ri = (RoleInfo) session.get(RoleInfo.class, (int)(su.getRole().intValue()));
				if(ri!=null)
					su.setRoleName(ri.getRoleName());
			}
			return list;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public SysUser merge(SysUser detachedInstance) {
		log.debug("merging SysUser instance");
		try {
			SysUser result = (SysUser) getSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(SysUser instance) {
		log.debug("attaching dirty SysUser instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(SysUser instance) {
		log.debug("attaching clean SysUser instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}